import time
import asyncio
import aiohttp

"""
背诵协程的原理
    生成器实现原理，实现了堆栈指令上惰性延迟功能的迭代器
实现一个协程程序
编写 asyncio 异步程序
编写 aiohttp 异步请求网站接口
"""


class Response:
    status_code = 200


def coroutine_avg():
    total, length = 0, 0
    while True:
        try:
            value = yield total / length
        except ZeroDivisionError:
            value = yield 0
        print(f"got send value {value}")
        total = value
        length += 1


# 编写 asyncio 异步程序
async def sim_request(i=0):
    response = Response()
    await asyncio.sleep(0.2)
    print(f'index {i}, current response {response.status_code}')
    return {i: response.status_code}


# aiohttp 异步请求网站接口
async def request_baidu(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            res = await response.text()
            return res

if __name__ == '__main__':
    # 实现协程程序
    num_avg = coroutine_avg()
    print(f'协程返回：{num_avg}')
    print(f'next执行后结果 {next(num_avg)}')
    print(f'传值 1 后返回结果：{num_avg.send(1)}')
    print(f'传值 2 后返回结果：{num_avg.send(3)}')
    print('-----------------')

    # asyncio 异步程序
    task_arr = []
    for i in range(10):
        res = sim_request(i)
        task_arr.append(res)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait([sim_request()]))
    print('多个task：')
    result = loop.run_until_complete(asyncio.gather(*task_arr))
    loop.close()
    print(result)
    print('-----------------')

    # aiohttp 异步请求网站接口
    url_array = ["https://www.163.com/"] * 10
    loop_1 = asyncio.get_event_loop()
    task_array = [request_baidu(url) for url in url_array]
    print(task_array)
    result_list = loop_1.run_until_complete(asyncio.gather(*task_array))
    loop_1.close()
    print(result_list)
